from concurrent.futures import ProcessPoolExecutor
import geopandas
from sqlalchemy import create_engine 
from geopandas import GeoDataFrame
import psycopg2
from osgeo import gdal
from osgeo import gdalconst
from osgeo import ogr
from osgeo import osr
import threading
import requests
import numpy as np
import datetime
import shutil
import random
import time
import math
import re
import os
import glob

# os.system(r"net use Z: \\192.168.2.172\root DELL123dell /user:root")

# clip raster by windows
def window_clip_raster(args):
	raster_path, save_folder, window, step = args

	raster_name = os.path.basename(raster_path)
	name = os.path.splitext(raster_name)[0]

	gdal.AllRegister()
	dataset = gdal.Open(raster_path)
	width,height = dataset.RasterXSize,dataset.RasterYSize
	projection = dataset.GetProjection()
	geotransform = dataset.GetGeoTransform()
	xmin, xsize = geotransform[0], geotransform[1]
	ymax, ysize = geotransform[3], geotransform[5]

	xcount = math.ceil((width-window[0])/step[0])
	ycount = math.ceil((height-window[1])/step[1])

	for x in range(xcount):
		for y in range(ycount):	
			left = xmin + x * step[0] * xsize
			right = left + window[0] * xsize
			top = ymax + y * step[1] * ysize
			bottom = top + window[1] * ysize
			outputBounds = (left, bottom, right, top)
			path = os.path.join(save_folder, f"{name}_{x}_{y}.tif")
			if not os.path.exists(path):
				gdal.Warp(
					path, 
					raster_path, 
					format='GTiff', 
					outputBounds=outputBounds, 
					outputBoundsSRS=projection, 
					multithread=10)
	return
# ogr连接数据库,读取数据
def task1():
    
    ogr.RegisterAll()
    url = 'postgresql://postgres:postgres@192.168.2.172:5432/sentinel2'
    conn= ogr.Open(url,update=1)
    sql = """select * from china_100km"""
    layer = conn.ExecuteSQL(sql)
    print(layer.GetName())
    feature = layer.GetNextFeature()
    while feature:
        # for i in feature.items(): print(i)
        feature = layer.GetNextFeature()
    conn.Destroy() 
    return
# ogr连接数据库，写入数据
def task2():
    sql = """select *
    from china_100km
    """
    ogr.RegisterAll()
    url = 'postgresql://postgres:postgres@192.168.2.172:5432/sentinel2'
    driver = ogr.GetDriverByName("PostgreSQL")
    dest_datasource = driver.CreateDataSource(url)
    dest_datasource.Destroy() 
    
    # url = 'postgresql://postgres:postgres@192.168.2.172:5432/sentinel2'
    # conn= ogr.Open(url,update=1)
    # layer = conn.ExecuteSQL(sql)
    # conn.
    # data.Destroy() 
    # conn.Destroy() 
    return

def task3(x,y):
    prosrs = osr.SpatialReference()
    prosrs.ImportFromEPSG(32650)
    geosrs = osr.SpatialReference()
    geosrs.ImportFromEPSG(4326)
    ct = osr.CoordinateTransformation(prosrs, geosrs)
    coords = ct.TransformPoint(x, y)[:2]
    print(coords)
    return

def is_writeable(path, check_parent=False):
    '''
    Check if a given path is writeable by the current user.
    :param path: The path to check
    :param check_parent: If the path to check does not exist, check for the
    ability to write to the parent directory instead
    :returns: True or False
    '''
    if os.access(path, os.F_OK) and os.access(path, os.W_OK):
    # The path exists and is writeable
        return True
    if os.access(path, os.F_OK) and not os.access(path, os.W_OK):
    # The path exists and is not writeable
        return False
    # The path does not exists or is not writeable
    if check_parent is False:
    # We're not allowed to check the parent directory of the provided path
        return False
    # Lets get the parent directory of the provided path
    parent_dir = os.path.dirname(path)
    if not os.access(parent_dir, os.F_OK):
    # Parent directory does not exit
        return False
    # Finally, return if we're allowed to write in the parent directory of the
    # provided path
    return os.access(parent_dir, os.W_OK)

def main():
    path = r"E:\Image2\S2B_MSIL1C_20220719T031529_N0400_R118_T49SED_20220719T051225.zip.incomplete"
    url="https://scihub.copernicus.eu/dhus/odata/v1/Products('6ca9b716-0921-49f6-9996-5cac2687f4cc')/$value"
    session = requests.Session()
    session.auth=('fyy_04', "show1234")
    # session.proxies={'http': '127.0.0.1:10809'}
    session.proxies={'http': '217.69.11.117:8080'}
    session.headers["User-Agent"]='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
    session.headers['Upgrade-Insecure-Requests']='1'
    session.headers.update({'Accept-Encoding': 'gzip, deflate, br'}) 
    session.headers.update({'Connection': 'keep-alive'}) 
    session.headers["Content-Type"]="application/json;charset=UTF-8"
    session.headers["Accept"]="ext/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
    session.headers["Accept-Language"]="zh-CN,zh;q=0.9,en;q=0.8"
    session.headers['Host']='scihub.copernicus.eu'
    session.headers['Referer']='https://scihub.copernicus.eu/dhus/'
    down_res = session.get(url,stream=True)
    cookie = session.cookies
    print(cookie)
    print(down_res.status_code)
    remote_host = down_res.raw._connection.sock.getpeername()
    remote_host_ip,remote_host_port = remote_host
    print(remote_host_ip,remote_host_port)
    local_host = down_res.raw._connection.sock.getsockname()
    local_host_ip,local_host_port = local_host
    print(local_host_ip,local_host_port)

    with open(path,'wb') as file:
        for chunk in down_res.iter_content(1024):	#防止文件过大，以1024为单位一段段写入
            file.write(chunk)
    # with open(path, 'wb') as file:
    #     iterator = down_res.iter_content(chunk_size=2 ** 20)
        # while True:
        #     chunk = next(iterator)
        #     if chunk: file.write(chunk)
       

    ''''''
    # source_folder = r"Z:\orange\source_tif"
    # txt_path = r"E:\ggcode.txt"
    # with open(txt_path, "w") as file:

    #     file.write
    #     for raster_name in os.listdir(source_folder):
    #         code = os.path.splitext(raster_name)[0]
    #         file.write(f"{code}\n")

    ''''''
    # source_folder = r"Z:\A01Image\Google_image\36_JiangXi\2022\赣州市\10"
    # target_folder = r"Z:\orange\clip_raster"
    # for name in os.listdir(source_folder):
    #     folder_name = os.path.splitext(name)[0]
    #     folder = os.path.join(target_folder, folder_name)
    #     if not os.path.exists(folder):
    #         os.makedirs(folder)
    ''''''
    # source_folder = r"Z:\orange\clip_png"
    # target_folder = r"Z:\orange\predict\pseudo_color_prediction"
    # pathre = os.path.join(source_folder, "*", "*.png.aux.xml")
    # paths = glob.glob(pathre)
    # for path in paths:
    #     name  = os.path.basename(path)
    #     target_path = os.path.join(target_folder,name)
    #     shutil.copyfile(path, target_path)
    #     print(target_path)
    ''''''
    # source_folder = r"Z:\orange\clip"
    # target_folder = r"Z:\orange\clip_raster"
    # for name in os.listdir(target_folder):
    #     paths = glob.glob(os.path.join(source_folder,f"{name}_*.tif"))
    #     for path in paths:
    #         shutil.move(path, os.path.join(target_folder, name))
    ''''''
    # n=0
    # folder = r"Z:\orange\result\added_prediction"
    # while True:
    #     for name in os.listdir(folder):
    #         if re.match("^.*\.png$", name):
    #             path = os.path.join(folder, name)
    #             result = is_writeable(path)
    #             print(result)
    #     n+=1
    #     print(f"第{n}次自检！")
    #     time.sleep(3)
    ''''''
    # base_folder = r"Z:\orange\clip_png"
    # mask_folder = r"Z:\orange\png"
    # for root,dir_names,file_names in os.walk(base_folder):
    #     for file_name in file_names:
    #         if re.match("^.*\.png$",file_name):
    #             mask_path = os.path.join(mask_folder, file_name)
    #             if os.path.join(mask_path):
    #                 base_path = os.path.join(root, file_name)
    #                 os.remove(base_path)
    #                 print(base_path)
    ''''''
    # source_dir = r"Z:\A01Image\Google_image\36_JiangXi\2022\赣州市"
    # count = 0
    # for root,dir_names,file_names in os.walk(source_dir):
    #     for file_name in file_names:
    #         if re.match("^.*\.(tif|jp2)$",file_name):
    #             count+=1
    #             # path = os.path.join(root, file_name)
    # print(count)
    ''''''
    # source_folder = r"Z:\冉志祎\image"
    # target_folder = r"Z:\冉志祎\temp"
    # for name in os.listdir(source_folder):
    #     path = os.path.join(source_folder,name)
    #     new_name = f"1000{name}"
    #     new_path = os.path.join(target_folder, new_name)
    #     shutil.copyfile(path, new_path)
    ''''''
    # source_dir = r"Z:\orange\xiugai_shp\dataset_label"
    # target_dir = r"Z:\orange\xiugai_shp\dataset\label"
    # args_list = []
    # for name in os.listdir(source_dir):
    #     # window_clip_raster([
    #     #     os.path.join(source_dir, name),
    #     #     target_dir,
    #     #     [512, 512],
    #     #     [512, 512]
    #     # ])
    #     args_list.append([
    #         os.path.join(source_dir, name),
    #         target_dir,
    #         [512, 512],
    #         [512, 512]
    #     ])
    # with ProcessPoolExecutor(4) as executor:
    #     executor.map(window_clip_raster, args_list)
    ''''''
    # base_folder = r"Z:\orange\source_tif"
    # mask_folder = r"Z:\orange\mege_shp"
    # dest_folder = r"Z:\orange\xiugai_shp\source_tif"
    # for name in os.listdir(base_folder):
    #     shp_name = name.replace(".jp2", ".shp")
    #     shp_path = os.path.join(mask_folder, shp_name)
    #     if not os.path.exists(shp_path):
    #         shutil.copyfile(
    #             os.path.join(base_folder, name),
    #             os.path.join(dest_folder, name)
    #         )
    '''filter file by name '''
    # source_folder = r"Z:\orange\result\pseudo_color_prediction"
    # target_folder = r"Z:\orange\xiugai_shp"
    # raster_flags = []
    # for name in os.listdir(source_folder):
    #     if re.match(".*\.png$", name):
    #         if name.split("_")[0] not in raster_flags:
    #             raster_flags.append(name.split("_")[0])
    # print(len(raster_flags))
    # for raster_flag in raster_flags:
    #     folder = os.path.join(target_folder, raster_flag) 
    #     if not os.path.exists(folder):
    #         os.makedirs(folder)
    #     pathre = os.path.join(source_folder, f"{raster_flag}*")
    #     paths = glob.glob(pathre)
    #     for path in paths:
    #         name = os.path.basename(path)
    #         copy_path = os.path.join(folder, name)
    #         shutil.copyfile(path, copy_path)
    return

def test():
    url = "http://192.168.1.73:2000/predict"
    files = [('files[]',('106千克 (1).jpg',open(r'E:\猪尸样本\106千克 (1).jpg','rb'),'image/jpeg'))]
    response = requests.post(url,files=files)
    
    print(response.text)
    return

if __name__ == "__main__":
    test()
    # print(3%5)
    # x,y = 600000,4300000
    # task3(x,y)
    # x,y = 700000,4200000
    # task3(x,y)
    # x,y = 600000,4200000
    # task3(x,y)
    # x,y = 700000,4300000
    # task3(x,y)